//
//  OneHomeViewController.swift
//  SwiftStudy
//
//  Created by chang on 2018/1/5.
//  Copyright © 2018年 chang. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import SDWebImage

class OneHomeViewController: UIViewController {

    fileprivate var textField : UITextField!
    fileprivate var scrollView : UIScrollView!
    fileprivate var tableView : UITableView!
    
    fileprivate var isBarSttyle : UIStatusBarStyle!
    fileprivate var topNavView : UIView!
    fileprivate var sureBtn : UIButton!
    fileprivate var historyBtn : UIButton!
    
    fileprivate let album_listArray = NSMutableArray.init()
    fileprivate let shufflingFigureArray = NSMutableArray.init()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.defaultBackgroundColor
        
        self.initTableView()
        
        self.tableHeadView()
        
        self.initTopView()
        
        self.requestShufflingFigureData()
        
        self.requestData(searchText: "仙剑奇侠传4") //default
    }

    func requestData(searchText: NSString) {
        self.view.makeToastActivity(.center)
        
        let urlString = "http://search.lekan.letv.com/leso/search.so?&wd=" + (searchText as String)
        let url = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.init(charactersIn: urlString))
        
        Alamofire.request(url!, method: .get).responseJSON {
            [weak self] (response) in
            self?.view.hideToastActivity()
            
            if let responseCC = response.result.value {
                let json = JSON(responseCC)
                let status = json["status"].string
                if status == "1" {
                    self?.album_listArray.removeAllObjects() //添加数据之前先清空一下数据
                    let album_list = json["data","album_list"].array
                    self?.album_listArray.addObjects(from: album_list!)
                    self?.tableView.reloadData()
                }
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: animated)
        UIApplication.shared.statusBarStyle = self.isBarSttyle //默认白色
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: animated)
        self.perform(#selector(changeBarStyle), with: nil, afterDelay: 0.01)
    }
    
    @objc func changeBarStyle() {
        UIApplication.shared.statusBarStyle = .default
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

//MARK: init navigationBar
extension OneHomeViewController : UITextFieldDelegate {
    
    func initTopView() {
        
        isBarSttyle = UIStatusBarStyle.lightContent
        
        let topView = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: MAINSCREEN_WIDTH, height: StatusBarHeight + self.navgationBarHeight))
        topView.image = UIImage.init(named: "firstHome_headBg")
        topView.isUserInteractionEnabled = true
        self.view.addSubview(topView)
        
        topNavView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: topView.width, height: topView.height))
        topNavView.backgroundColor = UIColor.white
        topNavView.alpha = 0
        topView.addSubview(topNavView)
        
        historyBtn = UIButton.init(type: .custom)
        historyBtn.frame = CGRect.init(x: topView.width-12-80, y: 20, width: 80, height: 40)
        historyBtn.backgroundColor = UIColor.clear
        historyBtn.setTitle("历史记录", for: .normal)
        historyBtn.setTitleColor(UIColor.white, for: .normal)
        historyBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        historyBtn.contentHorizontalAlignment = .right
        historyBtn.layer.cornerRadius = 5
        historyBtn.layer.masksToBounds = true
        historyBtn.addTarget(self, action: #selector(historyBtnClick(sender:)), for: .touchUpInside)
        topView.addSubview(historyBtn)
        
        sureBtn = UIButton.init(type: .custom)
        sureBtn.frame = CGRect.init(x: topView.width-12-historyBtn.width-5-40, y: historyBtn.top, width: 40, height: historyBtn.height)
        sureBtn.backgroundColor = historyBtn.backgroundColor
        sureBtn.setTitle("确定", for: .normal)
        sureBtn.setTitleColor(UIColor.white, for: .normal)
        sureBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        sureBtn.layer.cornerRadius = 5
        sureBtn.layer.masksToBounds = true
        sureBtn.addTarget(self, action: #selector(sureClickAction), for: .touchUpInside)
        topView.addSubview(sureBtn)

        textField = UITextField.init(frame: CGRect.init(x: 50, y: StatusBarHeight+6, width: topView.width-50-5-sureBtn.width-5-historyBtn.width-12, height: 30));
        textField.backgroundColor = UIColor.white
        textField.textColor = UIColor.defaultTextColor
        textField.borderStyle = .roundedRect
        textField.placeholder = "输入要搜索的内容🔍"
        textField.textAlignment = .center
        textField.font = UIFont.systemFont(ofSize: 15)
        textField.layer.masksToBounds = true
        textField.layer.cornerRadius = 10
        textField.layer.borderColor = UIColor.defaultLineColor.cgColor
        textField.layer.borderWidth = 1
        textField.returnKeyType = .search
        textField.delegate = self;
        topView.addSubview(textField)
    }
    
    public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.sureClickAction()
        return true
    }
    
    @objc func sureClickAction() {
        textField.resignFirstResponder()
        if textField.text?.isEmpty == true {
            self.view.makeToast("输入的内容为空哦", duration: 2.0, position: .center)
            return
        }else{
            self.requestData(searchText: textField.text! as NSString)
        }
    }
    
    @objc func historyBtnClick(sender: UIButton) {
        
    }
}
//MARK: init tableview
extension OneHomeViewController : UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate {
    
    func initTableView() {
        tableView = UITableView.init(frame: CGRect.init(x: 0, y: -StatusBarHeight, width: MAINSCREEN_WIDTH, height: MAINSCREEN_HEIGHT-self.tabBarHeight+StatusBarHeight))
        tableView.backgroundColor = UIColor.white
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        self.view.addSubview(tableView)
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.album_listArray.count
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 160
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "cell"
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        if cell == nil {
            cell = UITableViewCell.init(style: .default, reuseIdentifier: identifier)
            cell?.selectionStyle = .none
            
            let lrVar = CGFloat(8) //距离左右屏幕的间隔
            let image = UIImageView.init(frame: CGRect.init(x: lrVar, y: lrVar, width: 116, height: 160-lrVar*2))
            image.tag = 10
            image.backgroundColor = UIColor.defaultLineColor
            image.layer.borderColor = UIColor.defaultYellowColor.cgColor
            image.layer.borderWidth = 1;
            cell?.addSubview(image)
            
            let titleLabel = UILabel.init(frame: CGRect.init(x: image.right+5, y: image.top, width: tableView.width-image.right-5-5-60-lrVar, height: 18*2))
            titleLabel.tag = 11
            titleLabel.font = UIFont.boldSystemFont(ofSize: 15)
            titleLabel.textColor = UIColor.defaultTextColor
            titleLabel.numberOfLines = 2
            cell?.addSubview(titleLabel)
            
            let otherLabel = UILabel.init(frame: CGRect.init(x: titleLabel.left, y: titleLabel.bottom+5, width: titleLabel.width, height: 18*2))
            otherLabel.tag = 12
            otherLabel.font = UIFont.systemFont(ofSize: 14)
            otherLabel.textColor = UIColor.lightGray
            otherLabel.numberOfLines = 2
            cell?.addSubview(otherLabel)
            
            let ratingLabel = UILabel.init(frame: CGRect.init(x: titleLabel.right+5, y: titleLabel.top, width: 60, height: titleLabel.height))
            ratingLabel.tag = 13
            ratingLabel.font = UIFont.systemFont(ofSize: 15)
            ratingLabel.textColor = UIColor.defaultRedColor
            cell?.addSubview(ratingLabel)
            
            let playBtn = UIButton.init(type: .custom)
            playBtn.frame = CGRect.init(x: otherLabel.left, y: image.bottom-30-lrVar, width: 70, height: 30)
            playBtn.backgroundColor = UIColor.defaultYellowColor
            playBtn.isUserInteractionEnabled = false
            playBtn.setTitle("立即播放", for: .normal)
            playBtn.setTitleColor(UIColor.white, for: .normal)
            playBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            playBtn.layer.cornerRadius = 6
            playBtn.layer.masksToBounds = true
            playBtn.layer.borderColor = UIColor.defaultLineColor.cgColor
            playBtn.layer.borderWidth = 0.5
            cell?.addSubview(playBtn)
            
            let lineView = UIView.init(frame: CGRect.init(x: 0, y: 160-0.5, width: tableView.width, height: 0.5))
            lineView.backgroundColor = UIColor.defaultLineColor
            cell?.addSubview(lineView)
        }
        
        if let dic  = JSON(self.album_listArray.object(at: indexPath.row)).dictionary {
            let imageView = cell?.viewWithTag(10) as! UIImageView
            let imageUrl = (JSON(dic)["poster",0,"url"]).string
            imageView.sd_setImage(with: URL.init(string: imageUrl!), completed: nil)
            
            let titleLabel = cell?.viewWithTag(11) as! UILabel
            titleLabel.text = dic["name"]?.string
            
            let sub_category_name0 = JSON(dic)["sub_category",0,"name"].string
            let sub_category_name1 = JSON(dic)["sub_category",1,"name"].string
            let categoryName = ((sub_category_name0 == nil) ? "视频" : sub_category_name0!) + "|" + ((sub_category_name1 == nil) ? "影视" : sub_category_name1!)
            let episodes = "\n" + "总" + (dic["episodes"]?.string)! + "集"
            
            let otherLabel = cell?.viewWithTag(12) as! UILabel
            otherLabel.text = (dic["area_name"]?.string)! + "  " + categoryName + episodes
            
            let ratingLabel = cell?.viewWithTag(13) as! UILabel
            ratingLabel.text = "评分:" + ((dic["rating"]?.string != "") ? (dic["rating"]?.string)! : "无")
        }
        
        return cell!
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let dic  = JSON(self.album_listArray.object(at: indexPath.row)).dictionary {
            let videoUrl = JSON(dic)["video_list",0,"url"].string
            let webVC = CCWebViewController.init()
            webVC.webUrl = videoUrl! as NSString
            webVC.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(webVC, animated: true)
        }
    }
    
    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        textField.resignFirstResponder()
        
        // 计算当前偏移位置
        let offsetY = scrollView.contentOffset.y
        let coefficient = offsetY/120  //120是滑动比例系数
        topNavView.alpha = coefficient
        if (coefficient>0.6) {
            UIApplication.shared.statusBarStyle = .default
            isBarSttyle = UIStatusBarStyle.default
            
            sureBtn.setTitleColor(UIColor.black, for: .normal)
            historyBtn.setTitleColor(UIColor.black, for: .normal)
            textField.layer.borderColor = UIColor.defaultTextColor.cgColor
        }else{
            UIApplication.shared.statusBarStyle = .lightContent
            isBarSttyle = UIStatusBarStyle.lightContent
            
            sureBtn.setTitleColor(UIColor.white, for: .normal)
            historyBtn.setTitleColor(UIColor.white, for: .normal)
            textField.layer.borderColor = UIColor.defaultLineColor.cgColor
        }
    }
    
}

//MARK: Shuffling figure
extension OneHomeViewController {
    
    func tableHeadView() {
        scrollView = UIScrollView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.width, height: 240))
        scrollView.backgroundColor = UIColor.white
        scrollView.isPagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        tableView.tableHeaderView = scrollView
    }
    
    func requestShufflingFigureData() {
        self.view.makeToastActivity(.center)
        let url = "http://res.static.mojing.cn/171101-1-28-1/ios/zh/1/page/" + "443515.js"
        Alamofire.request(url,method: .get).responseJSON {
            [weak self] (response) in
            self?.view.hideToastActivity()
            if let responseCC = response.result.value {
                let json = JSON(responseCC)
                let status = json["status"].string
                if status == "0" {
                    self?.shufflingFigureArray.removeAllObjects()
                    let shufflingFigure = json["data","list",0,"list"].array
                    self?.shufflingFigureArray.addObjects(from: shufflingFigure!)
                    
                    DispatchQueue.main.async {
                        self?.freshShufflingFigure()
                    }
                }
            }
        }
    }
    
    func freshShufflingFigure() {
        scrollView.contentSize = CGSize.init(width: MAINSCREEN_WIDTH * CGFloat(self.shufflingFigureArray.count), height: scrollView.height)
        
        scrollView.removeAllSubviews()
        for (index,value) in self.shufflingFigureArray.enumerated() {
            let pic_url = JSON(value)["pic_url"].string
            let imageBtn = CCUIButton.init(type: .custom)
            imageBtn.frame = CGRect.init(x: MAINSCREEN_WIDTH*CGFloat(index), y: 0, width: MAINSCREEN_WIDTH, height: scrollView.height)
            imageBtn.sd_setImage(with: NSURL.init(string: pic_url!)! as URL, for: .normal)
            imageBtn.addTarget(self, action: #selector(headImageClickAction(sender:)), for: .touchUpInside)
            imageBtn.urlStr = JSON(value)["url"].string! as NSString
            scrollView.addSubview(imageBtn)
        }
    }
    
    @objc func headImageClickAction(sender: CCUIButton) {
        let playVC = VideoPlaybackViewController.init()
        playVC.urlStr = sender.urlStr
        playVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(playVC, animated: true)
    }
}

class CCUIButton : UIButton {
    var urlStr = NSString.init()
}


